package com.cry.flutter.admin.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.SignatureAlgorithm;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

public class JwtUtil {
    public static void main(String[] args) {
//        generalKey();
        String token = createJWT("testToken");
        Claims claims = parseJWT(token);
        claims.getSubject();

        System.out.println(claims.getSubject());

    }

    public static Claims parseJWT(String jwt) {
        PublicKey secretKey = generalKeyPair().getPublic();
        return Jwts.parser()
                .verifyWith(secretKey)
                .build().parseSignedClaims(jwt)
                .getPayload();
    }

    public static String createJWT(String subject) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        PrivateKey secretKey = generalKeyPair().getPrivate();
        JwtBuilder builder = Jwts.builder()
                .id("1")
                .subject(subject)   // 主题
                .issuer("user")     // 签发者
                .issuedAt(now)      // 签发时间
                .signWith(secretKey, Jwts.SIG.ES512); // 签名算法以及密匙
        return builder.compact();
    }

    public static KeyPair generalKeyPair() {
        // Create a test key suitable for the desired ECDSA signature algorithm:
        SignatureAlgorithm alg = Jwts.SIG.ES512; //or ES256 or ES384
        KeyPair pair = alg.keyPair().build();
        
        return pair;
    }
//     * 验证JWT
//     *
//     * @param jwtStr
//     * @return
//     */
//    public static CheckResult validateJWT(String jwtStr) {
//        CheckResult checkResult = new CheckResult();
//        Claims claims = null;
//        try {
//            claims = parseJWT(jwtStr);
//            checkResult.setSuccess(true);
//            checkResult.setClaims(claims);
//        } catch (ExpiredJwtException e) {
//            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);
//            checkResult.setSuccess(false);
//        } catch (SignatureException e) {
//            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
//            checkResult.setSuccess(false);
//        } catch (Exception e) {
//            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
//            checkResult.setSuccess(false);
//        }
//        return checkResult;
//    }
//


}
